// 设置页面的JavaScript代码

// 默认设置
const DEFAULT_SETTINGS = {
    highlight: false,
    quickFillEnabled: true,
    notificationsEnabled: true,
    keyboardShortcuts: true,
    autoBackup: false,
    theme: 'light',
    defaultOrderQty: 1
};

// DOM元素
const elements = {
    highlight: document.getElementById('highlight'),
    quickFillEnabled: document.getElementById('quickFillEnabled'),
    notificationsEnabled: document.getElementById('notificationsEnabled'),
    keyboardShortcuts: document.getElementById('keyboardShortcuts'),
    autoBackup: document.getElementById('autoBackup'),
    theme: document.getElementById('theme'),
    defaultOrderQty: document.getElementById('defaultOrderQty'),
    exportSettings: document.getElementById('exportSettings'),
    importSettings: document.getElementById('importSettings'),
    clearData: document.getElementById('clearData'),
    resetSettings: document.getElementById('resetSettings'),
    saveSettings: document.getElementById('saveSettings'),
    fileInput: document.getElementById('fileInput')
};

// 初始化
document.addEventListener('DOMContentLoaded', async () => {
    await loadSettings();
    bindEvents();
    applyTheme();
});

// 加载设置
async function loadSettings() {
    try {
        const result = await chrome.storage.sync.get(DEFAULT_SETTINGS);

        // 应用设置到界面
        elements.autoSave.checked = result.autoSave;
        elements.highlight.checked = result.highlight;
        elements.quickFillEnabled.checked = result.quickFillEnabled;
        elements.notificationsEnabled.checked = result.notificationsEnabled;
        elements.keyboardShortcuts.checked = result.keyboardShortcuts;
        elements.autoBackup.checked = result.autoBackup;
        elements.theme.value = result.theme;
        elements.defaultQuantity.value = result.defaultQuantity;

        console.log('设置已加载:', result);
    } catch (error) {
        console.error('加载设置失败:', error);
        showNotification('加载设置失败', 'error');
    }
}

// 保存设置
async function saveSettings() {
    try {
        const settings = {
            autoSave: elements.autoSave.checked,
            highlight: elements.highlight.checked,
            quickFillEnabled: elements.quickFillEnabled.checked,
            notificationsEnabled: elements.notificationsEnabled.checked,
            keyboardShortcuts: elements.keyboardShortcuts.checked,
            autoBackup: elements.autoBackup.checked,
            theme: elements.theme.value,
            defaultQuantity: parseInt(elements.defaultQuantity.value) || 10
        };

        await chrome.storage.sync.set(settings);

        // 应用主题
        applyTheme();

        // 通知后台脚本设置已更新
        chrome.runtime.sendMessage({
            action: 'settingsUpdated',
            settings: settings
        });

        showNotification('设置已保存', 'success');
        console.log('设置已保存:', settings);
    } catch (error) {
        console.error('保存设置失败:', error);
        showNotification('保存设置失败', 'error');
    }
}

// 重置设置
async function resetSettings() {
    if (confirm('确定要恢复默认设置吗？这将清除所有自定义设置。')) {
        try {
            await chrome.storage.sync.set(DEFAULT_SETTINGS);
            await loadSettings();
            applyTheme();
            showNotification('设置已重置为默认值', 'success');
        } catch (error) {
            console.error('重置设置失败:', error);
            showNotification('重置设置失败', 'error');
        }
    }
}

// 导出设置
async function exportSettings() {
    try {
        const settings = await chrome.storage.sync.get();
        const dataStr = JSON.stringify(settings, null, 2);
        const dataBlob = new Blob([dataStr], { type: 'application/json' });

        const url = URL.createObjectURL(dataBlob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `烟草订购助手设置_${new Date().toISOString().split('T')[0]}.json`;
        link.click();

        URL.revokeObjectURL(url);
        showNotification('设置已导出', 'success');
    } catch (error) {
        console.error('导出设置失败:', error);
        showNotification('导出设置失败', 'error');
    }
}

// 导入设置
function importSettings() {
    elements.fileInput.click();
}

// 处理文件导入
async function handleFileImport(event) {
    const file = event.target.files[0];
    if (!file) return;

    try {
        const text = await file.text();
        const settings = JSON.parse(text);

        // 验证设置格式
        if (typeof settings !== 'object') {
            throw new Error('无效的设置文件格式');
        }

        // 合并默认设置
        const mergedSettings = { ...DEFAULT_SETTINGS, ...settings };

        await chrome.storage.sync.set(mergedSettings);
        await loadSettings();
        applyTheme();

        showNotification('设置已导入', 'success');
    } catch (error) {
        console.error('导入设置失败:', error);
        showNotification('导入设置失败：' + error.message, 'error');
    }

    // 清空文件输入
    event.target.value = '';
}

// 清除所有数据
async function clearAllData() {
    if (confirm('确定要清除所有数据吗？这将删除所有设置和保存的订单数据，此操作不可恢复。')) {
        try {
            await chrome.storage.sync.clear();
            await chrome.storage.local.clear();
            await loadSettings();
            showNotification('所有数据已清除', 'success');
        } catch (error) {
            console.error('清除数据失败:', error);
            showNotification('清除数据失败', 'error');
        }
    }
}

// 应用主题
function applyTheme() {
    const theme = elements.theme.value;
    const body = document.body;

    body.classList.remove('dark-theme', 'light-theme');

    if (theme === 'dark') {
        body.classList.add('dark-theme');
    } else if (theme === 'light') {
        body.classList.add('light-theme');
    } else if (theme === 'auto') {
        // 跟随系统主题
        if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
            body.classList.add('dark-theme');
        } else {
            body.classList.add('light-theme');
        }
    }
}

// 绑定事件
function bindEvents() {
    // 保存按钮
    elements.saveSettings.addEventListener('click', saveSettings);

    // 重置按钮
    elements.resetSettings.addEventListener('click', resetSettings);

    // 导出按钮
    elements.exportSettings.addEventListener('click', exportSettings);

    // 导入按钮
    elements.importSettings.addEventListener('click', importSettings);

    // 文件输入
    elements.fileInput.addEventListener('change', handleFileImport);

    // 清除数据按钮
    elements.clearData.addEventListener('click', clearAllData);

    // 主题变化
    elements.theme.addEventListener('change', applyTheme);

    // 自动保存设置（当设置改变时）
    const autoSaveElements = [
        elements.highlight,
        elements.quickFillEnabled,
        elements.notificationsEnabled,
        elements.keyboardShortcuts,
        elements.autoBackup,
        elements.theme,
        elements.defaultOrderQty
    ];

    autoSaveElements.forEach(element => {
        if (element) {
            element.addEventListener('change', () => {
                // 延迟保存，避免频繁操作
                clearTimeout(window.autoSaveTimeout);
                window.autoSaveTimeout = setTimeout(saveSettings, 500);
            });
        }
    });

    // 监听系统主题变化
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
        if (elements.theme.value === 'auto') {
            applyTheme();
        }
    });

    // 键盘快捷键
    document.addEventListener('keydown', (e) => {
        if (e.ctrlKey && e.key === 's') {
            e.preventDefault();
            saveSettings();
        }
    });
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;

    // 添加样式
    Object.assign(notification.style, {
        position: 'fixed',
        top: '20px',
        right: '20px',
        padding: '12px 20px',
        borderRadius: '6px',
        color: 'white',
        fontWeight: '500',
        zIndex: '10000',
        transform: 'translateX(100%)',
        transition: 'transform 0.3s ease',
        maxWidth: '300px',
        wordWrap: 'break-word'
    });

    // 设置背景色
    switch (type) {
        case 'success':
            notification.style.background = '#28a745';
            break;
        case 'error':
            notification.style.background = '#dc3545';
            break;
        case 'warning':
            notification.style.background = '#ffc107';
            notification.style.color = '#212529';
            break;
        default:
            notification.style.background = '#17a2b8';
    }

    // 添加到页面
    document.body.appendChild(notification);

    // 显示动画
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);

    // 自动隐藏
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);

    // 点击隐藏
    notification.addEventListener('click', () => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    });
}

// 监听来自后台脚本的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'showNotification') {
        showNotification(request.message, request.type);
    }
});

// 页面卸载时保存设置
window.addEventListener('beforeunload', () => {
    if (window.autoSaveTimeout) {
        clearTimeout(window.autoSaveTimeout);
        saveSettings();
    }
});